import { User } from './../interfaces/request.interface';
import { ROLES_KEY } from './../decorator/roles.decorator';
import { Reflector } from '@nestjs/core';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector:Reflector){}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {

    const { user }:{user:User} = context.switchToHttp().getRequest();
    const roles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY,[context.getHandler(),context.getClass()]);
    
    if(!roles) {
      return true;
    }
    if(!user?.roles) {
      return false;
    }
    console.log(roles,user.roles);
    return roles.some(role => user.roles?.includes(role));
  }
}
